// 工单设置 运维部门
import type {
  operationsManageTableListDataItemType,
  formOperationsManageStateType
} from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElLink, ElIcon, ElSpace, ElDialog, ElButton, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import ProSaasTable from '~/components/ProSaasTable'
import AliIcon from '~/components/AliIocn'
import OperationsManageOption from './options/OperationsManageOption'
import styles from '~/pages/oam/index.module.scss'

export default defineComponent({
  name: 'OperationsManage',

  setup() {
    const store = useStore()

    // 初始值
    const proSaasTableRef = ref<ProSaasTableExposeType>() // 运维部门管理 列表
    const delRow = ref<operationsManageTableListDataItemType>() // 删除的行数据
    const formState = reactive<formOperationsManageStateType>({
      title: '', // 标题
      addOrEditShow: false, // 新增/编辑 弹窗是否显示
      delShow: false, // 删除 弹窗是否显示
      department: [], // 部门
      selCfgTypeName: [], // 当前运维部门们
      nowDynamicTags: [], // 当前工区们
      addList: [], // 工区原列表内容
      formAddDynamicTags: '', // 编辑工区时用, 实时显示是否可添加
      form: {
        deptId: '', // 部门id
        deptName: '', // 部门名
        dynamicTags: [], // 工区展示tag
        workAreaId: '', // 工区id
        workAreaName: '', // 工区名
        id: ''
      }
    })

    onMounted(() => {
      getDeptConfigListAjax() // 获取当前已有部门及工区们
      getDeptWorkareaListAjax(formState.nowDynamicTags!) // 获取所有工区
    })

    // 运维部门 主列表
    const columns: TableColumnProps<operationsManageTableListDataItemType>[] = [
      {
        label: '运维部门名称',
        prop: 'deptName',
        minWidth: 180,
        fixed: 'left',
        align: 'center'
      },
      {
        label: '对应工区',
        prop: 'workAreaName',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '操作',
        prop: 'options',
        minWidth: 180,
        fixed: 'right',
        align: 'center',
        render: ({ row }) => {
          return (
            <>
              <ElSpace>
                <ElLink type="primary" onClick={() => editOperationsManage(row)}>
                  <AliIcon type="icon-bianji" />
                  &nbsp;&nbsp;编辑
                </ElLink>
                &nbsp;&nbsp;
                {!row.status && (
                  <ElLink type="primary" onClick={() => delOperationsManage(row)}>
                    <AliIcon type="icon-shanchu" />
                    &nbsp;&nbsp;删除
                  </ElLink>
                )}
              </ElSpace>
            </>
          )
        }
      }
    ]

    // methods
    // 部门 及 部门是否可选
    const departmentAjax = async (valueDeptName?: string) => {
      const res = await store.dispatch('order/GetDeptTreeSelectList')
      if (res?.code === 200) {
        getDeptConfigListAjax() // 获取当前已选部门
        for (const i in res.data) {
          res.data[i].ifDisabled = false
          for (let j = 0; j < formState.selCfgTypeName!.length; j++) {
            const element = formState.selCfgTypeName![j]
            if (res.data[i].title === element && res.data[i].title !== valueDeptName) {
              res.data[i].ifDisabled = true
              break
            }
          }
        }
        formState.department = res.data
      }
    }

    // 获取当前已有部门及工区们
    const getDeptConfigListAjax = async () => {
      const params = {
        current: 1,
        size: 1000
      }
      const res = await store.dispatch('order/GetDeptConfigList', params)
      if (res?.code === 200) {
        formState.selCfgTypeName = []
        formState.nowDynamicTags = []

        for (const item in res.data.records) {
          const element = res.data.records[item]
          formState.selCfgTypeName.push(element.deptName) // 存当前运维部门
          // 获取当前列表的工区们
          if (element.workAreaName && element.workAreaName.match(/,/)) {
            formState.nowDynamicTags = formState.nowDynamicTags.concat(
              element.workAreaName.split(',')
            )
          } else {
            formState.nowDynamicTags.push(element.workAreaName)
          }
        }
      }
    }

    // 新增/编辑 工区 及 工区是否可添加
    const getDeptWorkareaListAjax = async (value: string[]) => {
      const params = {
        current: 1,
        size: 1000
      }
      const res = await store.dispatch('order/GetDeptWorkareaList', params)
      if (res?.code === 200) {
        for (const i in res.data.records) {
          res.data.records[i].ifDisabled = false
          for (let j = 0; j < value.length; j++) {
            if (res.data.records[i].name === value[j]) {
              res.data.records[i].ifDisabled = true
              break
            }
          }
        }
        formState.addList = res.data.records // 原列表内容
      }
    }

    // 新增
    const addOperationsManage = () => {
      formState.title = '新增运维部门管理'
      getDeptConfigListAjax() // 获取现有工区
      departmentAjax() // 部门
      formState.addOrEditShow = true
    }

    // 编辑 查看
    const editOperationsManage = async (row: operationsManageTableListDataItemType) => {
      formState.title = '编辑运维部门管理'
      getDeptConfigListAjax() // 获取现有工区
      formState.addOrEditShow = true
      formState.rowId = row.id
    }

    // 删除
    const delOperationsManage = (row?: operationsManageTableListDataItemType) => {
      formState.delShow = !formState.delShow
      if (formState.delShow) {
        delRow.value = row
      }
    }

    // 删除 提交
    const delSubmit = async () => {
      const res = await store.dispatch('order/PostDeptConfigRemove', delRow.value?.id) // 调删除接口
      if (res?.code === 200) {
        refreshTable() // 刷新列表
        delOperationsManage() // 关弹窗
        departmentAjax() // 更新 部门
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
      } else {
        ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
      }
    }

    // 刷新列表
    const refreshTable = () => {
      proSaasTableRef.value?.toSearch()
    }

    // 关闭
    const handleClose = () => {
      formState.form = {
        // 置空
        deptId: '', // 部门id
        deptName: '', // 部门名
        dynamicTags: [], // 工区展示tag
        workAreaId: '', // 工区id
        workAreaName: '', // 工区名
        id: ''
      }
      formState.rowId = undefined // 置空行id
      formState.addOrEditShow = false
    }

    return () => (
      <>
        <ElButton class={styles['orderSet-addBtn']} type="primary" onClick={addOperationsManage}>
          <ElIcon>
            <Plus />
          </ElIcon>
          &nbsp;&nbsp;新增
        </ElButton>
        <ProSaasTable<operationsManageTableListDataItemType>
          ref={proSaasTableRef}
          columns={columns}
          dispatchType="order/GetDeptConfigList" // 运维部门管理 主列表
        />

        {/* 新增、编辑 */}
        {formState.addOrEditShow && (
          <OperationsManageOption
            visible={formState.addOrEditShow}
            title={formState.title}
            rowId={formState.rowId}
            department={formState.department}
            addList={formState.addList}
            nowDynamicTags={formState.nowDynamicTags}
            onCancel={() => handleClose()}
            onDepartmentAjax={(value) => departmentAjax(value)}
            onRefreshTable={() => refreshTable()}
            onGetDeptWorkareaListAjax={(value) => getDeptWorkareaListAjax(value)}
          />
        )}

        {/* 删除 */}
        <ElDialog
          title="确认删除"
          modelValue={formState.delShow!}
          append-to-body
          width="22%"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={() => delOperationsManage()}
        >
          <div class={styles['orderSet-content']}>
            <div class={styles['orderSet-largeFont']}>确认删除{delRow.value?.deptName}</div>
            <div class={styles['orderSet-grayFont']}>删除后不可恢复，是否确认删除。</div>
          </div>
          <div class={styles['confirm-button']}>
            <ElButton
              class={styles['confirm-button-cancel']}
              plain
              onClick={() => delOperationsManage()}
            >
              取 消
            </ElButton>
            <ElButton class={styles['confirm-button-submit']} type="primary" onClick={delSubmit}>
              确 定
            </ElButton>
          </div>
        </ElDialog>
      </>
    )
  }
})
